package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;

import com.alibaba.android.arouter.utils.TextUtils;
import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.views.MyProgressDialog;
import com.haotunet.app.goldtreasure.views.SharePopupView;
import com.haotunet.app.goldtreasure.views.TitleView;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("deprecation")
public class GPriceTrendActivty extends BaseActivity {
    private View mRootView;
    private TitleView mTitleView;
    private WebView mWebView;
    private ShareStore shareStore;
    private String mTitle;
    private String mContent;
    private String mImageUrl;
    private String mUrl;
    private String mCurrentUrl;
    private Map<String, String> mTitlesMap = new HashMap<>();
    public static final int INIT_DATA_SUCCESS = 0x11;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case INIT_DATA_SUCCESS:
                    resetTitle("分享");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gold_price_trend);
        shareStore = new ShareStore(GPriceTrendActivty.this);
        initView();
    }

    private void initView() {
        String url = getIntent().getStringExtra("url");
        mRootView = findViewById(R.id.root);
        mTitleView = (TitleView) findViewById(R.id.title_view);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getRightText().setVisibility(View.VISIBLE);
        mTitleView.getRightText().setText("");
        mTitleView.getRightText().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    SharePopupView sharePopupView = new SharePopupView(GPriceTrendActivty.this, GPriceTrendActivty.this,
                            mUrl, mTitle, mContent, mImageUrl);
                    sharePopupView.showAtLocation(mRootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    ActivityUtils.backgroundAlpha(GPriceTrendActivty.this, 0.5f);
                    sharePopupView.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            ActivityUtils.backgroundAlpha(GPriceTrendActivty.this, 1f);
                        }
                    });
                }
            }
        });
        mTitleView.getBackView().setVisibility(View.VISIBLE);
        mTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                    resetTitle("");
                } else {
                    finish();
                }
            }
        });
        mWebView = (WebView) findViewById(R.id.webview_gtrend);
        CookieSyncManager.createInstance(GPriceTrendActivty.this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();
        cookieManager.setCookie(url, "_x-access-token=" + shareStore.getString(Strs.TOKEN, "")); // 你想设置的参数
        cookieManager.setCookie(url, "_version=" + shareStore.getString("versionName", "")); // 你想设置的参数
        cookieManager.setCookie(url, "_platform=android"); // 你想设置的参数
        cookieManager.setCookie(url, "Referer=api.goldplusgold.com");
        CookieSyncManager.getInstance().sync();
        mWebView.getSettings().setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        Map<String, String> extraHeaders = new HashMap<>();
        extraHeaders.put("Referer", "api.goldplusgold.com");
        mWebView.loadUrl(url, extraHeaders);
        mWebView.setWebViewClient(new WebViewClient() {
                                      @Override
                                      public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                          if (url.startsWith("tel:")) {
                                              Intent intent = new Intent(Intent.ACTION_VIEW,
                                                      Uri.parse(url));
                                              startActivity(intent);
                                              return true;
                                          }
                                          if (url.startsWith("http:") || url.startsWith("https:")) {
                                              view.loadUrl(url);
                                              return true;
                                          }
                                          return true;

                                      }

                                      @Override
                                      public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                                          handler.proceed();
                                      }

                                      @Override
                                      public void onPageStarted(WebView view, String url, Bitmap favicon) {
                                          super.onPageStarted(view, url, favicon);
                                          mCurrentUrl = url;
                                      }

                                      @Override
                                      public void onPageFinished(WebView view, String url) {
                                          super.onPageFinished(view, url);
                                          String title = mTitlesMap.get(url);
                                          if (!TextUtils.isEmpty(title)){
                                              mTitleView.getTitletextView().setText(title);
                                          }
                                      }
                                  }

        );

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setProgress(newProgress * 100);
                if (newProgress == 100) {
                    mWebView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (TextUtils.isEmpty(title)) {
                    title = "";
                }
                mTitlesMap.put(mCurrentUrl, title);
                mTitleView.getTitletextView().setText(title);
            }
        });
        mWebView.addJavascriptInterface(new JsOperation(mHandler), "android");
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            resetTitle("");
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    class JsOperation {
        public JsOperation(Handler handler) {

        }

        @JavascriptInterface
        public void makeOrder(int switchTab, String productId, String productName, int productType) {
            boolean isLogin = shareStore.getBoolean(Strs.IS_LOGIN, false);
            if (isLogin) {
                ActivityUtils.gotoBuyGold(GPriceTrendActivty.this, 2, productName, productId, switchTab, productType);
            } else {
                Intent intent = new Intent(GPriceTrendActivty.this, LoginActivity.class);
                startActivityForResult(intent, 1);
            }
        }

        @JavascriptInterface
        public void share(String title, String content, String imageUrl, String url) {
            mTitle = title;
            mContent = content;
            mImageUrl = imageUrl;
            mUrl = url;
            Message msg = new Message();
            msg.what = INIT_DATA_SUCCESS;
            mHandler.sendMessage(msg);
        }
    }

    private void resetTitle(String rightText) {
        mTitleView.getRightText().setText(rightText);
    }
}
